package com.sunnada.edu.system.pub.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.sunnada.edu.system.pub.cache.SysParam;



/**
 * 
 * 向外部系统发送http请求
 * 提供两个方法
 * 发送方式：参数是json格式
 * @author SESSION
 *
 */
public class HttpRequest {
	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpUrlSendRequest(String requestUrl, String RequestMethod, String output) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 建立连接
			URL url = new URL(requestUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(RequestMethod);
			if (output != null) {
				OutputStream out = connection.getOutputStream();
				out.write(output.getBytes("UTF-8"));
				out.close();
			}
			// 流处理
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input, "UTF-8");
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			// 关闭连接、释放资源
			reader.close();
			inputReader.close();
			input.close();
			input = null;
			connection.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());
			System.out.println("——————————————————————————————————————-http请求返回结果"+jsonObject.getString("msg"));
		} catch (Exception e) {
		}
		return jsonObject;
	}
	
	
	
	/**
	 * @param url
	 * @param json
	 * @return
	 * @throws Exception
	 */
	public static JSONObject httpPostSendRequest(String url, String json) throws Exception {
		JSONObject jsonObject = null;
        // 将JSON进行UTF-8编码,以便传输中文
        String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity se = new StringEntity(encoderJson);
        se.setContentType("text/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(se);
        HttpResponse hrs =httpClient.execute(httpPost);
        
        if (hrs.getStatusLine().getStatusCode() == HttpsURLConnection.HTTP_OK) {
			InputStream inputStream = hrs.getEntity().getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			// 将返回信息获取
			StringBuffer sb = new StringBuffer();
			String str;
			while ((str = reader.readLine()) != null) {
					sb.append(str);
			}
			reader.close();
			inputStream.close();
			inputStream=null;
			httpClient.getConnectionManager().shutdown();
			jsonObject = JSONObject.parseObject(sb.toString());
			System.out.println("——————————————————————————————————————-http请求返回结果"+jsonObject.getString("msg"));

		}
		return jsonObject;
    }
	
	
	/**
	 * @param url
	 * @param json
	 * @return
	 * @throws Exception
	 */
	public static JSONObject httpPostSendMultipartEntity(String url, MultipartEntity reqEntity) throws ClientProtocolException, IOException {
		System.out.println("修改显示头像 ...");

		// 自定义HttpClient 设置CookieStore
		CloseableHttpClient httpclient = HttpClients.custom().build();
		HttpPost request = new HttpPost(url);
		request.setEntity(reqEntity);

		CloseableHttpResponse response = httpclient.execute(request);
		String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

		// 解析JSON数据
		JSONObject resp = JSONObject.parseObject(responseBody);
		int result = resp.getIntValue("status");
		if (result == 1) {
			System.out.println("status:" + result + ",message:" + resp.getString("message"));
			System.out.println("facepath:" + resp.getJSONObject("data").getString("facepath"));
		} else {
			System.out.println("status:" + result + ",message:" + resp.getString("message"));
		}
		return resp;
	}
	
	
	public static void main(String[] args) throws Exception {
		UserBean user=new UserBean();
		user.setUserId("admin");
		user.setUserName("张三");
		String json=JSONObject.toJSONString(user);
		//String URL=SysParam.WORKER_URL_ADD;
		//HttpRequest.httpPostSendRequest(URL, json);
	}
	

	
	
}
